package example;

/**
 * A converter that parses a passed in String value for an Integer by converting the
 * String characters to their ASCII values.
 *
 * @author Dallas Rosson (dallasjrosson@gmail.com)
 * @version 1.0
 */
public class StringToIntConverter {
	
	/**
	 * Creates a new StringToIntConverter.
	 * @return 
	 */
	public StringToIntConverter() {
		
		// Default constructor.
	}
	
	// Utility methods.
	
	/**
	 * Converts a passed String to an Integer.
	 * 
	 * @param the_string The String to be converted.
	 * @return An Integer created from the passed in String.
	 * @throws IllegalArgumentException when the_string is equal to null.
	 * @throws IllegalArgumentException when the_string is empty ("").
	 * @throws IllegalArgumentException when any of the Strings characters are not capable
	 * of being converted to an Integer.
	 */
	public int convertStringToInt(final String the_string) {
		
		int retVal = 0;
		
		if (the_string == null || the_string.equals("")) { // the_string is null.
			
			throw new IllegalArgumentException();
			
		} else {

			int intLength = the_string.length(); // Element value of the future numbers.
			
			// Convert the String to an Array for easy parsing.
			char[] stringChars = the_string.toCharArray();
			
			for (int i = 0; i < stringChars.length; i++) {
				
				int val = stringChars[i]; // Get the ASCII value of the char.
				
				if (val < 48 || val > 57) { // char is not an integer.
					
					throw new IllegalArgumentException();
				}
							
				// Convert the char to its appropriate integer value.
				retVal += (int) ((val - 48) * (Math.pow(10, (intLength - 1))));
				
				intLength--;
			}			
		}
		
		return retVal;
	}
}
